﻿#include "C3fdAnalysisWidget.h"
#include "ui_C3fdAnalysisWidget.h"
#include "MainWindow/MainWindow.h"
#include "C3fdInputNameDialog.h"
#include <QMessageBox>
#include <QDir>
#include <QFile>
#include <QTextStream>

namespace MainWidget
{

	C3fdAnalysisWidget::C3fdAnalysisWidget(GUI::MainWindow *mainwindow, QWidget *parent) : QWidget(parent),
		m_Ui(new Ui::C3fdAnalysisWidget)
	{
		m_Ui->setupUi(this);
		m_Ui->lw_WorkingCondition->setSelectionBehavior(QAbstractItemView::SelectRows);
		m_Ui->lw_WorkingCondition->setSelectionMode(QAbstractItemView::SingleSelection);
		m_Ui->lw_WorkingCondition->setIconSize(QSize(16, 16));
		connect(m_Ui->lw_WorkingCondition, SIGNAL(itemClicked(QTreeWidgetItem *, int)), this, SLOT(itemClickedSlot(QTreeWidgetItem *, int)));
		connect(this, SIGNAL(displaySolveParameter(QTreeWidgetItem *, bool)), mainwindow, SIGNAL(updateSolveParameter(QTreeWidgetItem *, bool)));

		m_Project = Common::C3fdProject::instance();
		if (m_Project != nullptr)
		{
			m_CurrentCase = m_Project->getCurrentCase();
		}

		initWorkingConditionsList();

		connect(m_Ui->lw_WorkingCondition, SIGNAL(itemNameChanged(QTreeWidgetItem*, QString, QString, QString)), this, SLOT(itemNameChangedSlot(QTreeWidgetItem*, QString, QString, QString)));
	}

	C3fdAnalysisWidget::~C3fdAnalysisWidget()
	{
		delete m_Ui;
	}

	void C3fdAnalysisWidget::reTranslate()
	{
		m_Ui->retranslateUi(this);
	}

	void C3fdAnalysisWidget::itemClickedSlot(QTreeWidgetItem *item, int)
	{
		if (item != nullptr)
		{
			emit displaySolveParameter(item, m_Ui->lw_WorkingCondition->indexOfTopLevelItem(item) == 0);
		}
	}

	void C3fdAnalysisWidget::itemNameChangedSlot(QTreeWidgetItem* item, QString oldName, QString newName, QString action)
	{
		if (action == "add") {
			if (!addWorkingCondition(newName)) {
				m_Ui->lw_WorkingCondition->removeItemWidget(item, 0);
				delete item;
				item = nullptr;
			}
		}
		else if (action == "rename") {
			if (!renameWorkingCondition(oldName, newName)) {
				item->setText(0, oldName);
			}
		}
		else if (action == "delete") {
			if (deleteWorkingCondition(newName)) {
				m_Ui->lw_WorkingCondition->removeItemWidget(item, 0);
				delete item;
				item = nullptr;
			}
		}
	}

	bool C3fdAnalysisWidget::addWorkingCondition(QString name)
	{
		if (name.isEmpty())
		{
			return false;
		}

		if (m_CurrentCase->hasWorkCondition(name))
		{
			QMessageBox::critical(this, tr("Error Info"), QString(tr("Working Condition %1 already exists!")).arg(name));
			return false;
		}
		QDir dir;
		auto workingConditionsPath = m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator();
		if (dir.exists(workingConditionsPath + name))
		{
			dir.removeRecursively();
		}

		QString inputDir = workingConditionsPath + name + QDir::separator() + m_Project->getSolverInputDirName();
		QString outputDir = workingConditionsPath + name + QDir::separator() + m_Project->getSolverOutputDirName();
		if (dir.mkpath(inputDir) && dir.mkpath(outputDir))
		{

			Common::WorkCondition *wc = new Common::WorkCondition();
			auto existsWcs = m_CurrentCase->getWorkConditions();
			if (existsWcs.size() > 0)
			{
				auto firstWc = existsWcs.value(existsWcs.keys().at(0));
				if (firstWc != nullptr)
				{
					wc->setAirflowAngle(firstWc->getAirflowAngle());
					wc->setInletPress(firstWc->getInletPress());
					wc->setIntletTemp(firstWc->getIntletTemp());
					wc->setRotationSpeed(firstWc->getRotationSpeed());
				}
			}
			wc->setName(name);
			m_CurrentCase->addWorkCondition(wc);
			return true;
		}
		else
		{
			QMessageBox::critical(this, tr("Error Info"), tr("Failed to create folder!"));
			return false;
		}
	}

	bool C3fdAnalysisWidget::renameWorkingCondition(QString oldName, QString newName)
	{
		if (m_CurrentCase == nullptr)
		{
			QMessageBox::critical(this, tr("Error Info"), tr("System Error!"));
			return false;
		}

		if (oldName == newName)
		{
			return false;
		}
		QDir dir(m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator());
		if (dir.exists(newName))
		{
			QMessageBox::critical(this, tr("Error Info"), QString(tr("Folder %1 already exists!")).arg(newName));
			return false;
		}
		else
		{
			auto *wc = m_CurrentCase->getWorkConditions().value(oldName);
			if (wc != nullptr)
			{
				wc->setName(newName);
				m_CurrentCase->removeWorkCondition(oldName);
				m_CurrentCase->addWorkCondition(wc);
				if (dir.rename(oldName, newName))
				{
					return true;
				}
				else {
					return false;
				}
			}
			else {
				return false;
			}
		}
	}

	bool C3fdAnalysisWidget::deleteWorkingCondition(QString name)
	{
		if (m_CurrentCase == nullptr)
		{
			QMessageBox::critical(this, tr("Error Info"), tr("System Error!"));
			return false;
		}
		if (m_CurrentCase->hasWorkCondition(name))
		{
			QDir dir(m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator() + name);
			if (dir.removeRecursively())
			{
				m_CurrentCase->removeWorkCondition(name);
				return true;
			}
			else {
				return false;
			}
		}
		else
		{
			QMessageBox::critical(this, tr("Error Info"), QString(tr("No working condition named %1 found!")).arg(name));
			return false;
		}
	}

	void C3fdAnalysisWidget::initWorkingConditionsList()
	{
		m_Ui->lw_WorkingCondition->blockSignals(true);
		auto *currentCase = Common::C3fdProject::instance()->getCurrentCase();
		if (currentCase == nullptr)
		{
			return;
		}
		auto wcs = currentCase->getWorkConditions();
		m_Ui->lw_WorkingCondition->clear();

		// 工况排序
		QMap<int, QString> newWcs = {};
		for (auto k : wcs.keys())
		{
			newWcs.insert(wcs.value(k)->getOrder(), k);
		}

		for (auto k : newWcs.keys())
		{
			auto *item = new QTreeWidgetItem(m_Ui->lw_WorkingCondition);
			item->setText(0, newWcs.value(k));
			item->setIcon(0, QIcon(":/QUI/icon/c3fd_wc.png"));
			m_Ui->lw_WorkingCondition->addTopLevelItem(item);
		}
		m_Ui->lw_WorkingCondition->blockSignals(false);
	}

	void C3fdAnalysisWidget::on_pb_Add_clicked()
	{
		if (m_CurrentCase == nullptr)
		{
			QMessageBox::critical(this, tr("Error Info"), tr("System Error!"));
			return;
		}
		C3fdInputNameDialog dlg;
		if (dlg.exec() != QDialog::Accepted)
		{
			return;
		}
		QString name = dlg.getName();
		if (name.isEmpty())
		{
			return;
		}

		if (m_CurrentCase->hasWorkCondition(name))
		{
			QMessageBox::critical(this, tr("Error Info"), QString(tr("Working Condition %1 already exists!")).arg(name));
			return;
		}
		QDir dir;
		auto workingConditionsPath = m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator();
		if (dir.exists(workingConditionsPath + name))
		{
			dir.removeRecursively();
		}

		QString inputDir = workingConditionsPath + name + QDir::separator() + m_Project->getSolverInputDirName();
		QString outputDir = workingConditionsPath + name + QDir::separator() + m_Project->getSolverOutputDirName();
		if (dir.mkpath(inputDir) && dir.mkpath(outputDir))
		{

			Common::WorkCondition *wc = new Common::WorkCondition();
			auto existsWcs = m_CurrentCase->getWorkConditions();
			if (existsWcs.size() > 0)
			{
				auto firstWc = existsWcs.value(existsWcs.keys().at(0));
				if (firstWc != nullptr)
				{
					wc->setAirflowAngle(firstWc->getAirflowAngle());
					wc->setInletPress(firstWc->getInletPress());
					wc->setIntletTemp(firstWc->getIntletTemp());
					wc->setRotationSpeed(firstWc->getRotationSpeed());
				}
			}
			wc->setName(name);
			m_CurrentCase->addWorkCondition(wc);
			auto *item = new QTreeWidgetItem(m_Ui->lw_WorkingCondition);
			item->setText(0, name);
			item->setIcon(0, QIcon(":/QUI/icon/c3fd_wc.png"));
			m_Ui->lw_WorkingCondition->addTopLevelItem(item);
		}
		else
		{
			QMessageBox::critical(this, tr("Error Info"), tr("Failed to create folder!"));
		}
	}

	void C3fdAnalysisWidget::on_pb_Remove_clicked()
	{
		if (m_CurrentCase == nullptr)
		{
			QMessageBox::critical(this, tr("Error Info"), tr("System Error!"));
			return;
		}
		auto selectedItems = m_Ui->lw_WorkingCondition->selectedItems();
		if (selectedItems.length() == 1 && m_CurrentCase->hasWorkCondition(selectedItems.at(0)->text(0)))
		{
			auto *item = selectedItems.at(0);
			QDir dir(m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator() + item->text(0));
			if (dir.removeRecursively())
			{
				m_CurrentCase->removeWorkCondition(item->text(0));
				int index = m_Ui->lw_WorkingCondition->indexOfTopLevelItem(item);
				if (index < 0)
					return;
				m_Ui->lw_WorkingCondition->takeTopLevelItem(index);
				delete item;
				item = nullptr;
			}
		}
		else
		{
			QMessageBox::critical(this, tr("Error Info"), tr("Please select a working condition!"));
		}
	}

	void C3fdAnalysisWidget::on_pb_Rename_clicked()
	{
		if (m_CurrentCase == nullptr)
		{
			QMessageBox::critical(this, tr("Error Info"), tr("System Error!"));
			return;
		}
		auto selectedItems = m_Ui->lw_WorkingCondition->selectedItems();
		if (selectedItems.length() == 1)
		{
			C3fdInputNameDialog dlg(selectedItems.at(0)->text(0));
			if (dlg.exec() != QDialog::Accepted)
			{
				return;
			}
			QString name = dlg.getName();
			auto *item = selectedItems.at(0);
			auto oldName = item->text(0);
			if (oldName == name)
			{
				return;
			}
			QDir dir(m_Project->getCurrentProjectDir() + m_Project->getWorkingConditionDirName() + QDir::separator());
			if (dir.exists(name))
			{
				QMessageBox::critical(this, tr("Error Info"), QString(tr("Folder %1 already exists!")).arg(name));
			}
			else
			{
				auto *wc = m_CurrentCase->getWorkConditions().value(oldName);
				if (wc != nullptr)
				{
					wc->setName(name);
					m_CurrentCase->removeWorkCondition(oldName);
					m_CurrentCase->addWorkCondition(wc);
				}
				if (dir.rename(oldName, name))
				{
					item->setText(0, name);
				}
			}
		}
		else
		{
			QMessageBox::critical(this, tr("Error Info"), tr("Please select a working condition!"));
		}
	}

}
